{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.3 Building a heap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.3-1\n",
    "\n",
    "> Using Figure 6.3 as a model, illustrate the operation of BUILD-MAX-HEAP on the array $A = \\left \\langle 5, 3, 17, 10, 84, 19, 6, 22, 9 \\right \\rangle$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](img/6.3-1_1.png)\n",
    "\n",
    "MAX-HEAPIFY$(A, 4)$: $A = \\left \\langle 5, 3, 17, 22, 84, 19, 6, 10, 9 \\right \\rangle$\n",
    "\n",
    "![](img/6.3-1_2.png)\n",
    "\n",
    "MAX-HEAPIFY$(A, 3)$: $A = \\left \\langle 5, 3, 19, 22, 84, 17, 6, 10, 9 \\right \\rangle$\n",
    "\n",
    "![](img/6.3-1_3.png)\n",
    "\n",
    "MAX-HEAPIFY$(A, 2)$: $A = \\left \\langle 5, 84, 19, 22, 3, 17, 6, 10, 9 \\right \\rangle$\n",
    "\n",
    "![](img/6.3-1_4.png)\n",
    "\n",
    "MAX-HEAPIFY$(A, 1)$: $A = \\left \\langle 84, 22, 19, 10, 3, 17, 6, 5, 9 \\right \\rangle$\n",
    "\n",
    "![](img/6.3-1_5.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.3-2\n",
    "\n",
    "> Why do we want the loop index $i$ in line 2 of BUILD-MAX-HEAP to decrease from $\\left \\lfloor A.length/2 \\right \\rfloor$ to $1$ rather than increase from $1$ to $\\left \\lfloor A.length/2 \\right \\rfloor$?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To ensure the subtrees are heaps."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.3-3\n",
    "\n",
    "> Show that there are at most $\\left \\lceil n/2^{h+1} \\right \\rceil$ nodes of height $h$ in any $n$-element heap."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$$\n",
    "\\frac{n - \\left \\lceil n / 2 \\right \\rceil}{2^h} = \\left \\lceil \\frac{n}{2^{h+1}} \\right \\rceil\n",
    "$$"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
